package com.yequan.thread.pc;

public class Table {

    private int head; //下一次取蛋糕的位置
    private int tail; //下一次放置蛋糕的位置
    private int count;//当前桌子存放的蛋糕数量
    private String[] buffer;

    public Table(int count) {
        this.buffer = new String[count];
        this.head = 0;
        this.tail = 0;
        this.count = 0;
    }

    /**
     * 蛋糕师放置蛋糕:
     * 当桌子上当前蛋糕数量大于等于桌子容量时,停止放置蛋糕
     *
     * @param cake
     */
    public synchronized void put(String cake) throws InterruptedException {
        System.out.println(Thread.currentThread().getName() + " 做好一个蛋糕,取名为 " + cake);
        while (count >= buffer.length) {
            wait();
        }
        //放置蛋糕
        buffer[tail] = cake;
        //确定下一次放置蛋糕的位置
        tail = (tail + 1) % buffer.length;
        count++;
        notifyAll();

    }

    /**
     * 消费者取蛋糕:
     * 当桌子上的蛋糕数量小于或等于0时,停止取蛋糕
     *
     * @return
     */
    public synchronized String take() throws InterruptedException {
        while (count <= 0) {
            wait();
        }
        //取蛋糕
        String cake = buffer[head];
        //确定下一次去蛋糕店的位置
        head = (head + 1) % buffer.length;
        count--;
        notifyAll();
        System.out.println(Thread.currentThread().getName() + " 取走了一个蛋糕,取走的蛋糕名为 " + cake);
        return cake;
    }

}
